package com.coolingme.springboot.sentinel;

import com.alibaba.csp.sentinel.Entry;
import com.alibaba.csp.sentinel.SphO;
import com.alibaba.csp.sentinel.SphU;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.RuleConstant;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager;

import java.util.ArrayList;
import java.util.List;

/**
 * @author wangyue
 * @date 2022/10/18 10:27
 */
public class SentinelDemo {

    public static void main(String[] args) {
        // 初始化限流规则
        initFlowRule();
        while (true) {
            // 第一种方式 SphU获取资源并释放
            try (Entry entry = SphU.entry("resource")) {
                System.out.println(entry);
            } catch (BlockException e) {
                System.out.println("资源被拒");
            }

            // 第二种方式 SphO获取资源
            if (SphO.entry("resource")) {
                System.out.println("*********************");
                // 释放资源
                SphO.exit();
            } else {
                System.out.println("资源被拒");
            }
        }

    }

    /**
     * 初始化限流规则
     *
     * @author wangyue
     * @date 2022/10/18 10:34
     */
    private static void initFlowRule() {
        List<FlowRule> flowRuleList = new ArrayList<>();
        FlowRule flowRule = new FlowRule();
        // 设置资源
        flowRule.setResource("resource");
        // 限流阈值的类型 QPS（每秒查询率）或者并发数
        flowRule.setGrade(RuleConstant.FLOW_GRADE_QPS);
        // 限制并发数
        flowRule.setGrade(RuleConstant.FLOW_GRADE_THREAD);
        // 设置QPS为5
        flowRule.setCount(5);
        flowRuleList.add(flowRule);
        // 加载限流规则
        FlowRuleManager.loadRules(flowRuleList);
    }

}
